<template>
  <div class="lucene-search-container">
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchForm" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="18">
            <el-form-item label="搜索内容">
              <el-input 
                v-model="searchForm.keywords" 
                placeholder="请输入搜索关键词"
                @keyup.enter.native="handleSearch"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="文档类型">
              <el-select v-model="searchForm.type" placeholder="请选择文档类型" clearable>
                <el-option label="文章" value="article" />
                <el-option label="分类" value="category" />
                <el-option label="标签" value="tag" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: right">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <el-card class="result-card" v-loading="loading">
      <div slot="header">
        <span>搜索结果 (共 {{ total }} 条)</span>
      </div>
      
      <div v-if="searchResults.length === 0 && searchPerformed" class="no-results">
        <el-empty description="暂无搜索结果" />
      </div>
      
      <el-table 
        v-else 
        :data="searchResults" 
        stripe 
        style="width: 100%"
        :show-header="false"
      >
        <el-table-column prop="title" label="标题">
          <template #default="scope">
            <div class="result-item">
              <div class="result-title" @click="viewDetail(scope.row)">
                {{ scope.row.title }}
              </div>
              <div class="result-content" v-html="scope.row.content"></div>
              <div class="result-meta">
                <el-tag size="mini" :type="getTypeTagType(scope.row.type)">
                  {{ getTypeDisplayName(scope.row.type) }}
                </el-tag>
                <span class="result-id">ID: {{ scope.row.id }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-if="total > 0"
        @current-change="handlePageChange"
        :current-page="searchForm.pageNum"
        :page-size="searchForm.pageSize"
        :total="total"
        layout="total, prev, pager, next, jumper"
        style="margin-top: 20px; text-align: center"
      />
    </el-card>
  </div>
</template>

<script>
import { searchDocument, searchDocumentByType } from '@/api/cms/lucene'

export default {
  name: 'LuceneSearch',
  data() {
    return {
      searchForm: {
        keywords: '',
        type: '',
        pageNum: 1,
        pageSize: 10
      },
      searchResults: [],
      total: 0,
      loading: false,
      searchPerformed: false
    }
  },
  created() {
    // 组件创建时可以执行默认搜索
  },
  methods: {
    handleSearch() {
      if (!this.searchForm.keywords.trim()) {
        this.$message.warning('请输入搜索关键词')
        return
      }
      
      this.searchForm.pageNum = 1
      this.performSearch()
    },
    
    performSearch() {
      this.loading = true
      this.searchPerformed = true
      
      const query = {
        query: this.searchForm.keywords,
        pageNum: this.searchForm.pageNum,
        pageSize: this.searchForm.pageSize
      }
      
      const searchPromise = this.searchForm.type 
        ? searchDocumentByType(this.searchForm.type, query)
        : searchDocument(query)
      
      searchPromise.then(response => {
        if (response.code === 200) {
          this.searchResults = response.data.map(item => ({
            id: item.id,
            title: item.title || item.name,
            content: this.highlightKeywords(item.content || item.description || ''),
            type: item.type
          }))
          this.total = response.total
        } else {
          this.$message.error('搜索失败: ' + response.msg)
          this.searchResults = []
          this.total = 0
        }
      }).catch(error => {
        console.error('搜索出错:', error)
        this.$message.error('搜索请求失败')
        this.searchResults = []
        this.total = 0
      }).finally(() => {
        this.loading = false
      })
    },
    
    handlePageChange(page) {
      this.searchForm.pageNum = page
      this.performSearch()
    },
    
    resetForm() {
      this.searchForm = {
        keywords: '',
        type: '',
        pageNum: 1,
        pageSize: 10
      }
      this.searchResults = []
      this.total = 0
      this.searchPerformed = false
    },
    
    viewDetail(row) {
      // 根据不同类型跳转到不同的详情页面
      switch (row.type) {
        case 'article':
          this.$router.push(`/cms/article/detail/${row.id}`)
          break
        case 'category':
          this.$router.push(`/cms/category/detail/${row.id}`)
          break
        case 'tag':
          this.$router.push(`/cms/tag/detail/${row.id}`)
          break
        default:
          this.$message.info('暂不支持查看该类型详情')
      }
    },
    
    highlightKeywords(content) {
      // 高亮已经在后端处理，直接返回内容
      if (!content) return ''
      // 截取内容前200个字符
      return content.length > 200 ? content.substring(0, 200) + '...' : content
    },

    getTypeDisplayName(type) {
      const typeMap = {
        'article': '文章',
        'category': '分类',
        'tag': '标签'
      }
      return typeMap[type] || type
    },
    
    getTypeTagType(type) {
      const typeMap = {
        'article': 'primary',
        'category': 'success',
        'tag': 'warning'
      }
      return typeMap[type] || 'info'
    }
  }
}
</script>

<style scoped>
.lucene-search-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.result-card {
  min-height: 400px;
}

.result-item {
  padding: 10px 0;
}

.result-title {
  font-size: 16px;
  font-weight: bold;
  color: #1890ff;
  cursor: pointer;
  margin-bottom: 8px;
}

.result-title:hover {
  text-decoration: underline;
}

.result-content {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 8px;
}

.highlight {
  color: #f56c6c;
  font-weight: bold;
}

.result-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.result-id {
  font-size: 12px;
  color: #999;
}

.no-results {
  text-align: center;
  padding: 40px 0;
}
</style>